package jjn.round1;

/**
 * @author Jjn
 * @since 2022/9/11 00:43
 */
public class LeetCode463_IslandPerimeter {
    public int islandPerimeter(int[][] grid) {
        int height = grid.length;
        int width = grid[0].length;
        int total = 0;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (grid[i][j] == 1) {
                    total += dfs(grid, j, i);
                }
            }
        }
        return total;
    }

    private int dfs(int[][] grid, int i, int j) {
        int height = grid.length;
        int width = grid[0].length;
        if (i < 0 || i >= width || j < 0 || j >= height || grid[j][i] == 0) {
            return 1;
        }
        if (grid[j][i] == 2) {
            return 0;
        }
        grid[j][i] = 2;
        int left = dfs(grid, i - 1, j);
        int right = dfs(grid, i + 1, j);
        int upper = dfs(grid, i, j - 1);
        int lower = dfs(grid, i, j + 1);
        return left + right + upper + lower;
    }
}
